\chapter{Examples}
In this chapter we jump right in and write a number of short example extensions to HeaDSET via the official APIs. These are meant to give you a feel of how they should be written. All examples can be found in the examples directory, so you don't have to type them out yourself. 

\section{Setting up}
First of all you should have a working version of \headset and we recommend you to look at the user manual for the installation procedure.  In your \headset directory you should find a peripherals directory. There you will find the \verb|IntputController| and \verb|OutputController|.  
\subsection{OutputControllers}
OutputControllers can be bound to the system in \verb|Main.py|. Just find the start-up function and make a new instance of your \verb|OutputController| and it should work automatically.  The examples described, can be enabled by removing the code that has been commented out with an example in it.
\subsection{InputControllers}
If you have a \verb|TimedInputController| you can easily install it by adding it in at nearly the same way as an OutputController. You do have to make your own \verb|InputWrapper| instance and start your \verb|InputController|. For more low-level \verb|InputControllers| you will have to modify the GUI controller code. \footnote{The PathRecorder application has some support for adding InputControllers. Another example of how InputControllers can be wrapped, can be found in the playback application.}
\subsection{Examples}
The main.py module contains a number of examples and they are normally commented out. But you can enable them simply by removing these comments. \verb|OutputController| examples are present in modeling view and \verb|InputController| examples are present in the recording view. 

\section{Output}
We will write two examples. In the first example you will encounter level 1 events and in the second example we will write an extension that makes use of level 2 and level 3 events. 
\subsection{Simple logger} 
We begin by making a simple skeleton class. This will be used throughout the entire tutorial. 
\begin{verbatim}
# SimpleLogger example

from peripherals import OutputController

class SimpleLogger(OutputController):
	
   def __init__(self):
       #call the OutputController constructor
       OutputController.__init__(self)
\end{verbatim}
Now we are goinig to add a number of methods that print a bit of information on the console. To run this program you have to run HeaDSET in development mode. First we add two methods, \verb|GeomAdded| and \verb|GeomRemoved|.
The results should looks like this:
\begin{verbatim}	
    def GeomAdded(self, geom):
        print "Geom added"
	
    def GeomRemoved(self, geom):
        print "Geom removed"
\end{verbatim}
If we add or remove a geom we see a message appear on the console. It would be nice if we could see if a geom is updated and if we could distinguish between geoms. This is what we are goinig to do in the next example.
\begin{verbatim}
    def GeomUpdated(self, geom):
        print geom.GetLabel() + " " + str(geom.GetID()) + " updated"
\end{verbatim}
Here we use the geom argument to get some properties. We wrap the GetID method with str(), because that method returns an integer. Now we know how to listen to geoms, we can also apply this to instruments. To listen to equivalent instrument events, just replace 'Geom' (in the name 'GeomUpdated') by the term 'Instrument' in the example.
 
\subsection{Advanced logger}
As we saw in the previous example just listening to events isn't all that exciting. In the next example we are goinig to look at level 2 and level 3 events. We need a bit more boilerplate than the basic skeleton, because we are dealing with file IO. 
\begin{verbatim}
class AdvancedLogger(OutputController):
    def __init__(self):
        #call the OutputController constructor
        OutputController.__init__(self)
        self.__log = open("AdvancedLogger.log", 'w')
	
    def __del__(self):
        #flush the log
        self.__log.flush()
		
        # close journal
        self.__log.close()	
\end{verbatim}
This code is needed to open and close the logfile succesfully. Now we can add actual methods to our class. It would be nice to know if the position of the geom changes. We can do this as follows:

\begin{verbatim}
    def GeomPositionUpdated(self, geom):
        #get the position of the geom.
        x,y,z = geom.GetPosition()

        #get the id of the geom
        id = geom.GetID()

        #write position to log
        self.__log.write("Geom " + str(id) + " now at :" + str(x) + "," + str(y) + "," + str(z))
\end{verbatim}
We first get the position from the geom argument and then we write this to the log. You can also listen to Scale and Rotation events and these work in the same way. Only the name of the methods changes, but the arguments stay the same.
But sometimes we need to listen to more precise events. Maybe we want to listen to changes of the x-component of scaling a geom. This can be done like overriding the \verb|InstrumentScaleXUpdated| method:

\begin{verbatim}
    def InstrumentScaleXUpdated(self, instrument):
        #get the scale of the geom
        x,y,z = geom.GetScale()

        #get the id of the geom
        id = geom.GetPosition()

        #write to log
        self.__log.write("Geom " + xstr(id) + " x scalled to " + str(x) + "\n")
\end{verbatim}

\section{InputControllers}
Here we write two extensions. First we write a little formula based on T\verb|imedInputController|. And afterwards we make a new example by making use of the joystick (this joystick is not as advanced as the one used in the actual \headset application, but it should be able to explain what is needed).
Now you should have the basic idea of what you can do with an output controller. With this short tutorial and the API documentation you should be able to make your own OutputControllers.

\section{InputControllers}
InputControllers are very different compared to OutputControllers. All input to the system goes via a \verb|InputInterface| that abstracts you from the underlying system. 
\subsection{Forwarder}
In this example we will make a simple \verb|TimedInputController| that will move the instrument forward.  We start with a simple skeleton.
\begin{verbatim}
from peripherals import TimedInputController
from peripherals import InputInterface

class Forwarder(TimedInputController):
    def __init__(self, inputInterface):
        TimedInputController.__init__(self, inputInterface, 40)

    def DoWork(self):
        pass
\end{verbatim}
As you can see, we need two components from the peripherals package. The first program we write will change the orientation and the position of the instrument by a constant factor. To do this, we change the body of the methods to the following:
\begin{verbatim}
    def __init__(self, inputInterface):
        TimedInputController.__init__(self, inputInterface, 40)
        self.__x = 0
        self.__phi = 0
		
    def DoWork(self):
        interface = self._inputInterface
        self.__x = 1 + self.__x
        self.__phi = 1 + self.__phi
        interface.SetPositionInstrument(self.__x, 0,0)
        interface.SetOrientationInstrument(0, 0,self.__phi)
\end{verbatim}

We define some instance variables and modify these during a \verb|DoWork| cycle. These modified values are fed to the \verb|inputInterface|, which then communicates the values to the underlying \headset system.  
\subsection{Simple joystick}
Now we know how to make a simple \verb|TimedInputController|, we are now starting to make a simple joystick controller. We start with the \verb|InputController| skeleton. Because we need access to the joystick, we also need to include the wxPython package. This gives us the \verb|self.__js| instance variable of type \verb|wx.Joystick|. In the \verb|DoWork| method we poll the wx.Joystick and manipulate the input for consumption by the \headset environment. The SimpleJoyStick looks like this:

\begin{verbatim}
import wx		
		
class SimpleJoystickController(TimedInputController):
    def __init__(self, inputInterface):
        self.__js = wx.Joystick()
        TimedInputController.__init__(self, inputInterface, 30)

    def DoWork(self):
        #poll the joystick
        x,y = self.__js.GetPosition()
        b = self.__js.GetButtonState()

        #transform the value's to something a bit more workable
        x = (x - self.__js.GetXMax()/2.0) / (4.0 * self.__js.GetXMax())
        y = (y - self.__js.GetYMax()/2.0) / (4.0 * self.__js.GetYMax())
        z = 0
		
        #handle the button presses
        if b == 1:
            z = -0.5
        if b == 2:
            z = 0.5
		
        #get information about the position of the instrument
        xo, yo, zo = self._inputInterface.GetPositionInstrument()

        #map joystick values to the HeaDSET world
        xn = xo + x
        yn =  yo - y
        zn = zo + z
		
        #insert the values into HeaDSET
        self._inputInterface.SetPositionInstrument(xn, yn, zn)	
\end{verbatim}
In \headset there's a more advanced joystick example if you want to learn more about interacting with \headset. The \verb|PlayBackController| is also a good place to look for ideas on how to interact with \headset. 
